﻿using IdleTest.EFAndMVCDemo.IRepositories;
using IdleTest.EFAndMVCDemo.Models;
using IdleTest.EFAndMVCDemo.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace IdleTest.EFAndMVCDemo.Repositories
{
    public class UserRepository : IUserRepository, IDisposable
    {
        private SqlFileContext dbContext;
        private DbSet<UserModel> UserModelSet;

        public UserRepository(SqlFileContext dbContext)
        {
            this.dbContext = dbContext;
            this.UserModelSet = this.dbContext.Users;
        }

        public IEnumerable<UserModel> Get(
            Expression<Func<UserModel, 
            bool>> filter = null, 
            Func<IQueryable<UserModel>, 
            IOrderedQueryable<UserModel>> orderBy = null, 
            string includeProperties = "")
        {
            IQueryable<UserModel> query = UserModelSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public UserModel GetSingle(string id)
        {
            return this.UserModelSet.Find(id);
        }

        public void Insert(UserModel entity)
        {
            this.UserModelSet.Add(entity);
            this.dbContext.SaveChanges();
        }

        public void Update(UserModel entityToUpdate)
        {
            UserModelSet.Attach(entityToUpdate);
            dbContext.Entry(entityToUpdate).State = EntityState.Modified;
            this.dbContext.SaveChanges();
        }

        public void Delete(string id)
        {
            var entityToDelete = GetSingle(id);
            Delete(entityToDelete);
        }

        public void Delete(UserModel entityToDelete)
        {
            if (dbContext.Entry(entityToDelete).State == EntityState.Detached)
            {
                UserModelSet.Attach(entityToDelete);
            }
            UserModelSet.Remove(entityToDelete);
            this.dbContext.SaveChanges();
        }

        public void Dispose()
        {
            if (this.dbContext != null)
            {
                this.dbContext.Dispose();
            }
        }
    }
}
